import XLSX from "xlsx";
var fs = require("fs");

var dictionary_data = {};
var cr = {
    prepareDictionary: function (path, err) {
        dictionary_data = {};
        var workbook;

        //读取excel
        var data;
        try {
            data = fs.readFileSync(path, "binary"); //, function(err, data) {
        } catch (e) {
            console.log(e.message);
            return false;
        }

        try {
            workbook = XLSX.read(data, { type: "binary" }); // 以二进制流方式读取得到整份excel表格对象
        } catch (e) {
            console.log("多语言表表读取失败" + e.message);
            return false;
        }

        // 遍历每张表读取
        var is_dictionary_empty = true;
        for (var sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {

                //转为json对象进行验证操作
                var json = XLSX.utils.sheet_to_json(workbook.Sheets[sheet], { header: 1 });
                for (var i = 0; i < json.length; i++) {
                    if (json[i][0].indexOf('&') == 0) {
                        dictionary_data[json[i][0]] = json[i][1];
                        is_dictionary_empty = false;
                    }
                }

                if (is_dictionary_empty) {
                    console.log("多语言表没有有效的替换内容");
                    return false;
                }
                return true;
            }
        }
        console.log("没有sheet");
        return false;
    },
    replace: function (srcData, err) {
        var replaceCount = 0;
        for (var i = 1; i < srcData.length; i++) {
            if (srcData[i].length <= 0)
                continue;
            var row_data = srcData[i];
            if (!row_data ||!row_data[0] || typeof(row_data[0]) != "string"||row_data[0].indexOf('#') == 0)
                continue;

            for (var j = 0; j < row_data.length; j++) {
                var value = row_data[j];
                if (value&&value.length && value.length > 1) {
                    //if (value[0] == '&' && value[value.length - 1] == '&') {
                        if (dictionary_data[value]) {
                            row_data[j] = dictionary_data[value];
                            replaceCount++;
                        }
                        else {
                            err.msg = "<" + value + ">没有对应的替换内容";
                            return false;
                        }

                    //}
                }
            }
        }
        err.dyy_count = replaceCount;
        return true;
    }
}
export default cr;